package com.sanjishu.enterlab.electricity.sale.controller.manage;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.service.AdminService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/manage")
public class ManageSignUpController {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value  = "/login", method = RequestMethod.GET)
    public String loginView() {
        return "/manage/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Response login(String passport, String password) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(passport, DigestUtils.md5Hex(password));
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return Response.getError("账号或密码不正确!");
        }
        return Response.buildSuccess("");
    }

    @RequestMapping(value = "/forgetpassword", method = RequestMethod.GET)
    public String forgetPassword() {
        return "/manage/forgetPassword";
    }

    @RequestMapping(value="modifyPwd",method= RequestMethod.POST)
    @ResponseBody
    public Response modifyPwd(String phone, String password, HttpServletRequest request){
        return adminService.updatePassword(phone, password);
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/manage/login";
    }
}
